package com.haopeng.gateway.zuul.filter;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StringUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * zuul 过滤器
 *  注意：此为zuul 1.x版本 的写法；2.x版本于此不同
 * @author Administrator
 */
public class TokenFilter extends ZuulFilter {
	  private final Logger logger = LoggerFactory.getLogger(TokenFilter.class);
	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		logger.info("--->>> TokenFilter {},{}", request.getMethod(), request.getRequestURL().toString());
		  String token = request.getHeader("token");// 获取请求的参数
		if (!StringUtils.isEmpty(token)) {
            ctx.setSendZuulResponse(true); //对请求进行路由
            ctx.setResponseStatusCode(200);
            ctx.set("success", true);
        } else {
            ctx.setSendZuulResponse(false); //不对其进行路由
            ctx.setResponseStatusCode(400);
            ctx.setResponseBody("token is empty");
            ctx.set("success", false);
        }
		return null;
	}

	@Override
	public boolean shouldFilter() {
		// 是否执行该过滤器，此处为true，说明需要过滤
		return true;
	}

	@Override
	public int filterOrder() {
		// filter执行顺序，通过数字指定 ,优先级为0，数字越大，优先级越低
		return 0;
	}

	@Override
	public String filterType() {
		// 定义filter的类型，有pre、route、post、error四种
		return FilterConstants.PRE_TYPE; // 可以在请求被路由之前调用
	}

}
